package com.cskaoyan.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.cskaoyan.mall.commons.exception.ValidateException;
import com.cskaoyan.user.constants.UserRetCode;
import com.cskaoyan.user.dal.entitys.Member;
import com.cskaoyan.user.dal.entitys.UserVerify;
import com.cskaoyan.user.dal.persistence.MemberMapper;
import com.cskaoyan.user.dal.persistence.UserVerifyMapper;
import com.cskaoyan.user.dto.UserRegisterRequest;
import com.cskaoyan.user.dto.UserRegisterResponse;
import com.cskaoyan.user.service.IRegisterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.UUID;


/**
 * ClassName: IRegisterServiceImpl
 * Description:
 * date: 2022/6/18 11:32
 *
 * @author bruce
 * @since JDK 8
 */
@Service
@Slf4j
public class IRegisterServiceImpl implements IRegisterService {

    @Autowired
    MemberMapper memberMapper;

    @Autowired
    UserVerifyMapper userVerifyMapper;

    @Autowired
    JavaMailSender mailSender;

    @Override
    public UserRegisterResponse register(UserRegisterRequest registerRequest) {
        UserRegisterResponse response = new UserRegisterResponse();
        //判空验证
        registerRequest.requestCheck();

        //验证用户名是否重复
        volidUserNameRepeat(registerRequest);
        //验证邮箱是否重复
        volidEmailRepeat(registerRequest);

        //1.向用户表中插入一条记录
        Member member = new Member();
        member.setUsername(registerRequest.getUserName());
        member.setEmail(registerRequest.getEmail());
        //md5加密处理
        String userpassword = DigestUtils.md5DigestAsHex(registerRequest.getUserPwd().getBytes());
        member.setPassword(userpassword);
        member.setCreated(new Date());
        member.setUpdated(new Date());
        member.setIsVerified("N");
        member.setState(1);
        int effectRows = memberMapper.insert(member);
        if (effectRows != 1) {
            response.setCode(UserRetCode.USER_REGISTER_FAILED.getCode());
            response.setMsg(UserRetCode.USER_REGISTER_FAILED.getMessage());
            return response;
        }
        //2.向用户验证表中插入一条记录
        UserVerify userVerify = new UserVerify();
        userVerify.setUsername(member.getUsername());
        String key = member.getUsername() + member.getPassword() + UUID.randomUUID().toString();
        String uuid = DigestUtils.md5DigestAsHex(key.getBytes());
        userVerify.setUuid(uuid);
        userVerify.setRegisterDate(new Date());
        userVerify.setIsExpire("N");
        userVerify.setIsVerify("N");
        int effectRows2 = userVerifyMapper.insert(userVerify);
        if (effectRows2 != 1) {
            response.setCode(UserRetCode.USER_REGISTER_VERIFY_FAILED.getCode());
            response.setMsg(UserRetCode.USER_REGISTER_VERIFY_FAILED.getMessage());
            return response;
        }
        //3.发送用户激活邮件 TODO 消息中间件MQ
        sendEmail(uuid,registerRequest);

        //打印日志
        log.info("用户注册成功，注册参数request：{}",JSON.toJSONString(registerRequest));
        //用户注册成功
        response.setCode(UserRetCode.SUCCESS.getCode());
        response.setMsg(UserRetCode.SUCCESS.getMessage());
        return response;
    }

    /**
    * Description: 发送用户激活邮件
    * @date: 2022/6/20 15:34
    * @param:
    * @return:
    */
    private void sendEmail(String uuid, UserRegisterRequest registerRequest) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject("CSMALL用户激活");
        message.setTo(registerRequest.getEmail());
        message.setFrom("1132045742@qq.com");
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("http://localhost:8099/user/verify?uuid=").append(uuid).append("&username=").append(registerRequest.getUserName());
        message.setText(stringBuilder.toString());
        mailSender.send(message);
    }

    private void volidUserNameRepeat(UserRegisterRequest registerRequest) {
        Example example = new Example(Member.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("username",registerRequest.getUserName());
        List<Member> members = memberMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(members)) {
            throw new ValidateException(UserRetCode.USERNAME_ALREADY_EXISTS.getCode(),UserRetCode.USERNAME_ALREADY_EXISTS.getMessage());
        }
    }
    private void volidEmailRepeat(UserRegisterRequest registerRequest) {
        Example example = new Example(Member.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("email",registerRequest.getEmail());
        List<Member> members = memberMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(members)) {
            throw new ValidateException(UserRetCode.EMAIL_ALREADY_EXISTS.getCode(),UserRetCode.EMAIL_ALREADY_EXISTS.getMessage());
        }
    }
}
